﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

using Core.Common;

namespace DataReceiver.DataAPI
{
    public class SqlOperater
    {
        public static bool InsertTicks(List<Model_Tick> ticks)
        {
            bool isSuccess = true;
            using(SqlConnection conn = new SqlConnection(ConfigHelper.SqlServerConnectionstring))
            {
                //建立连接
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;

                //遍历插入
                foreach(var tick in ticks)
                {
                    StringBuilder sql = new StringBuilder();
                    sql.Append(@"INSERT INTO [future_tick].[dbo].[tick]
                                       ([instrument_id]
                                       ,[last_price]
                                       ,[bid_price]
                                       ,[bid_vol]
                                       ,[ask_price]
                                       ,[ask_vol]
                                       ,[volume]
                                       ,[open_interest]
                                       ,[update_time])
                                 VALUES");
                    sql.Append(" (");
                    sql.Append(" '" + tick.InstrumentID + "'");
                    sql.Append(" ," + tick.LastPrice);
                    sql.Append(" ," + tick.BidPrice);
                    sql.Append(" ," + tick.BidVolume);
                    sql.Append(" ," + tick.AskPrice);
                    sql.Append(" ," + tick.AskVolume);
                    sql.Append(" ," + tick.Volume);
                    sql.Append(" ," + tick.OpenInterest);
                    sql.Append(" ,'" + tick.UpdateTime.AddHours(8).ToString("yyyy-MM-dd HH:mm:ss.fff") + "'");
                    sql.Append(" )");

                    //捕获插入异常
                    cmd.CommandText = sql.ToString();
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch(SqlException ex)
                    {
                        //除了唯一约束，其他判定为插入错误
                        if (!ex.Message.Contains(@"违反了 UNIQUE KEY 约束“唯一性”"))
                        {
                            LogTextHelper.WriteLine("插入tick失败：" + ex.Message);
                            isSuccess = false;
                        }

                        //维护连接
                        if (conn.State == ConnectionState.Closed && conn.State == ConnectionState.Broken)
                        {
                            conn.Close();
                            conn.Open();
                        }
                    }
                }
                conn.Close();
                return isSuccess;
            }
        }
    }
}
